<template>
  <!-- 悬浮按钮 -->
  <div 
    v-if="!chatVisible"
    class="ai-chat-button"
    :style="buttonStyle"
    @mousedown="startDrag"
    @click="openChat"
  >
    <el-icon :size="28"><ChatDotRound /></el-icon>
    <div class="pulse-ring"></div>
  </div>

  <!-- 聊天窗口 -->
  <div 
    v-if="chatVisible"
    class="ai-chat-window"
    :style="windowStyle"
  >
    <!-- 标题栏（可拖动） -->
    <div class="chat-header" @mousedown="startDrag">
      <div class="header-left">
        <el-icon :size="20"><ChatDotRound /></el-icon>
        <span class="header-title">AI智能助手</span>
      </div>
      <div class="header-actions">
        <el-button 
          text 
          circle 
          @click="minimizeChat"
          :icon="Minus"
        />
        <el-button 
          text 
          circle 
          @click="closeChat"
          :icon="Close"
        />
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="(msg, index) in messages" 
        :key="index"
        :class="['message-item', msg.role]"
      >
        <div class="message-avatar">
          <el-icon v-if="msg.role === 'user'" :size="24"><User /></el-icon>
          <el-icon v-else :size="24"><Service /></el-icon>
        </div>
        <div class="message-content">
          <div class="message-text" v-html="formatMessage(msg.content)"></div>
          <div class="message-time">{{ msg.time }}</div>
        </div>
      </div>

      <!-- AI正在输入提示 -->
      <div v-if="isTyping" class="message-item assistant typing-indicator">
        <div class="message-avatar">
          <el-icon :size="24"><Service /></el-icon>
        </div>
        <div class="message-content">
          <div class="typing-dots">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>

      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        <el-alert :title="errorMessage" type="error" :closable="false" />
      </div>
    </div>

    <!-- 输入框 -->
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="2"
        placeholder="请输入您的问题..."
        @keydown.enter.exact="handleSend"
        :disabled="isTyping"
      />
      <el-button 
        type="primary" 
        :icon="Promotion"
        @click="handleSend"
        :loading="isTyping"
        :disabled="!inputMessage.trim()"
      >
        发送
      </el-button>
    </div>

    <!-- 快捷问题 -->
    <div class="quick-questions" v-if="messages.length === 0">
      <div class="quick-title">常见问题：</div>
      <el-tag 
        v-for="(q, index) in quickQuestions" 
        :key="index"
        @click="selectQuickQuestion(q)"
        class="quick-tag"
      >
        {{ q }}
      </el-tag>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import { ChatDotRound, Close, Minus, User, Service, Promotion } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance();

// 悬浮按钮位置
const buttonPosition = ref({ x: window.innerWidth - 80, y: window.innerHeight - 80 });
const windowPosition = ref({ x: window.innerWidth - 420, y: 100 });

// 拖动相关
const isDragging = ref(false);
const dragStart = ref({ x: 0, y: 0 });
const dragTarget = ref(null); // 'button' 或 'window'

// 聊天状态
const chatVisible = ref(false);
const messages = ref([]);
const inputMessage = ref('');
const isTyping = ref(false);
const errorMessage = ref('');
const messagesContainer = ref(null);

// 快捷问题
const quickQuestions = ref([
  '如何创建订单？',
  '库存查询怎么操作？',
  '发货流程是什么？',
  '如何查看实时库存？'
]);

// 按钮样式
const buttonStyle = computed(() => ({
  left: `${buttonPosition.value.x}px`,
  top: `${buttonPosition.value.y}px`
}));

// 窗口样式
const windowStyle = computed(() => ({
  left: `${windowPosition.value.x}px`,
  top: `${windowPosition.value.y}px`
}));

// 开始拖动
const startDrag = (e) => {
  e.preventDefault();
  isDragging.value = true;
  dragStart.value = { x: e.clientX, y: e.clientY };
  
  // 判断是拖动按钮还是窗口
  dragTarget.value = chatVisible.value ? 'window' : 'button';
  
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
};

// 拖动中
const onDrag = (e) => {
  if (!isDragging.value) return;
  
  const deltaX = e.clientX - dragStart.value.x;
  const deltaY = e.clientY - dragStart.value.y;
  
  if (dragTarget.value === 'button') {
    buttonPosition.value = {
      x: Math.max(0, Math.min(window.innerWidth - 60, buttonPosition.value.x + deltaX)),
      y: Math.max(0, Math.min(window.innerHeight - 60, buttonPosition.value.y + deltaY))
    };
  } else {
    windowPosition.value = {
      x: Math.max(0, Math.min(window.innerWidth - 400, windowPosition.value.x + deltaX)),
      y: Math.max(0, Math.min(window.innerHeight - 500, windowPosition.value.y + deltaY))
    };
  }
  
  dragStart.value = { x: e.clientX, y: e.clientY };
};

// 停止拖动
const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

// 打开聊天窗口
const openChat = () => {
  if (isDragging.value) return; // 如果是拖动，不触发打开
  chatVisible.value = true;
  
  // 如果是首次打开，显示欢迎消息
  if (messages.value.length === 0) {
    messages.value.push({
      role: 'assistant',
      content: '您好！我是AI智能助手，有什么可以帮助您的吗？',
      time: getCurrentTime()
    });
  }
};

// 最小化聊天窗口
const minimizeChat = () => {
  chatVisible.value = false;
};

// 关闭聊天窗口
const closeChat = () => {
  chatVisible.value = false;
};

// 选择快捷问题
const selectQuickQuestion = (question) => {
  inputMessage.value = question;
  handleSend();
};

// 发送消息
const handleSend = async (e) => {
  // 如果是Shift+Enter，允许换行
  if (e && e.shiftKey) {
    return;
  }
  
  if (e) {
    e.preventDefault();
  }
  
  const message = inputMessage.value.trim();
  if (!message || isTyping.value) return;
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: message,
    time: getCurrentTime()
  });
  
  inputMessage.value = '';
  errorMessage.value = '';
  isTyping.value = true;
  
  // 滚动到底部
  await nextTick();
  scrollToBottom();
  
  try {
    // 调用后端API（流式）
    await sendMessageStream(message);
  } catch (error) {
    console.error('发送消息失败:', error);
    errorMessage.value = '发送失败，请稍后重试';
    ElMessage.error('AI服务暂时不可用');
  } finally {
    isTyping.value = false;
  }
};

// 发送消息（流式）
const sendMessageStream = async (message) => {
  try {
    const response = await fetch(`${proxy.http.ipAddress}api/AICustomerService/chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ message })
    });

    if (!response.ok) {
      throw new Error('网络请求失败');
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    
    let aiMessage = {
      role: 'assistant',
      content: '',
      time: getCurrentTime()
    };
    messages.value.push(aiMessage);

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value);
      const lines = chunk.split('\n');

      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim();
          
          if (data === '[DONE]') {
            console.log('✅ AI响应完成');
            await nextTick();
            scrollToBottom();
            return;
          }

          try {
            const parsed = JSON.parse(data);
            
            if (parsed.error) {
              errorMessage.value = parsed.message;
              return;
            }

            if (parsed.choices && parsed.choices[0]?.delta?.content) {
              aiMessage.content += parsed.choices[0].delta.content;
              await nextTick();
              scrollToBottom();
            }
          } catch (e) {
            // 忽略解析错误
          }
        }
      }
    }
  } catch (error) {
    console.error('流式请求失败:', error);
    throw error;
  }
};

// 格式化消息（支持换行）
const formatMessage = (content) => {
  return content.replace(/\n/g, '<br>');
};

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 组件卸载时清理事件监听
onUnmounted(() => {
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
});
</script>

<style scoped lang="less">
// 悬浮按钮
.ai-chat-button {
  position: fixed;
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: move;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: transform 0.2s, box-shadow 0.2s;
  z-index: 9999;
  user-select: none;

  &:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.25);
  }

  &:active {
    transform: scale(0.95);
  }

  .pulse-ring {
    position: absolute;
    width: 100%;
    height: 100%;
    border: 2px solid #667eea;
    border-radius: 50%;
    animation: pulse 2s infinite;
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.5;
  }
  100% {
    transform: scale(1.4);
    opacity: 0;
  }
}

// 聊天窗口
.ai-chat-window {
  position: fixed;
  width: 400px;
  height: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  z-index: 9999;
  overflow: hidden;

  // 标题栏
  .chat-header {
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: move;
    user-select: none;

    .header-left {
      display: flex;
      align-items: center;
      gap: 10px;

      .header-title {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .header-actions {
      display: flex;
      gap: 5px;

      .el-button {
        color: white;
        
        &:hover {
          background: rgba(255, 255, 255, 0.2);
        }
      }
    }
  }

  // 消息列表
  .chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background: #f5f7fa;

    .message-item {
      display: flex;
      gap: 12px;
      margin-bottom: 20px;
      animation: slideIn 0.3s ease;

      &.user {
        flex-direction: row-reverse;

        .message-content {
          align-items: flex-end;

          .message-text {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
          }
        }
      }

      &.assistant {
        .message-text {
          background: white;
          color: #333;
        }
      }

      .message-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: #e0e6ed;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
      }

      .message-content {
        display: flex;
        flex-direction: column;
        gap: 4px;
        max-width: 70%;

        .message-text {
          padding: 12px 16px;
          border-radius: 12px;
          line-height: 1.5;
          word-wrap: break-word;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .message-time {
          font-size: 12px;
          color: #999;
          padding: 0 4px;
        }
      }
    }

    // 正在输入动画
    .typing-indicator {
      .typing-dots {
        display: flex;
        gap: 4px;
        padding: 12px 16px;
        background: white;
        border-radius: 12px;

        span {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: #999;
          animation: bounce 1.4s infinite ease-in-out both;

          &:nth-child(1) {
            animation-delay: -0.32s;
          }

          &:nth-child(2) {
            animation-delay: -0.16s;
          }
        }
      }
    }

    .error-message {
      margin: 10px 0;
    }
  }

  // 输入框
  .chat-input {
    padding: 16px 20px;
    background: white;
    border-top: 1px solid #e0e6ed;
    display: flex;
    gap: 10px;
    align-items: flex-end;

    .el-input {
      flex: 1;
    }

    .el-button {
      height: 60px;
    }
  }

  // 快捷问题
  .quick-questions {
    padding: 12px 20px;
    background: #f5f7fa;
    border-top: 1px solid #e0e6ed;

    .quick-title {
      font-size: 12px;
      color: #999;
      margin-bottom: 8px;
    }

    .quick-tag {
      margin: 4px;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

// 滚动条样式
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;

  &:hover {
    background: #555;
  }
}
</style>

